package city.spring.modules.system.controller;

import city.spring.modules.system.dto.ResetPasswordDTO;
import city.spring.modules.system.entity.PermissionEntity;
import city.spring.modules.system.entity.RoleEntity;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.PermissionService;
import city.spring.modules.system.service.RoleService;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import city.spring.utils.OrganizationUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息 控制器
 *
 * @author HouKunLin
 * @date 2019/12/20 0020 11:00
 */
@RestController
@RequestMapping("/user")
public class UserController extends ApiController {
    /**
     * 用户信息 Service
     */
    private final UserService userService;
    private final RoleService roleService;
    private final PermissionService permissionService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<UserEntity, ?>> entityOrderFields;

    public UserController(UserService userService, RoleService roleService, PermissionService permissionService) {
        this.userService = userService;
        this.roleService = roleService;
        this.permissionService = permissionService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(UserEntity::getId);
        entityOrderFields.add(UserEntity::getNickname);
        entityOrderFields.add(UserEntity::getUsername);
        entityOrderFields.add(UserEntity::getPhone);
        entityOrderFields.add(UserEntity::getEmail);
        entityOrderFields.add(UserEntity::getGmtCreate);
        entityOrderFields.add(UserEntity::getGmtModified);
    }

    /**
     * 忽略对当前用登录户信息的操作
     *
     * @param user   当前登录用户
     * @param userId 前端提交的用户ID
     */
    @ModelAttribute
    public void ignoreCurrentUser(@NonNull Principal user, @PathVariable(required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return;
        }
        if (userId.equals(user.getName())) {
            throw new RuntimeException("不能操作当前登录用户信息");
        }
    }

    /**
     * 获取所有用户信息
     *
     * @param pageable 分页参数
     * @param entity   查询内容
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.list')")
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, UserEntity entity) {
        LambdaQueryChainWrapper<UserEntity> lambdaQuery = buildLambdaQuery(entity);
        OrganizationUtils.includes(lambdaQuery, UserEntity::getOrgId);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 获取可以使用的用户列表（前端选择用户时使用的用户列表）
     *
     * @param pageable 分页信息
     */
    @GetMapping("selectUserList")
    public Object selectUserList(@PageableDefault Pageable pageable, UserEntity entity) {
        LambdaQueryChainWrapper<UserEntity> lambdaQuery = buildLambdaQuery(entity);
        OrganizationUtils.includes(lambdaQuery, UserEntity::getOrgId);
        lambdaQuery.select(UserEntity::getId, UserEntity::getNickname, UserEntity::getUsername, UserEntity::getPhone);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<UserEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 分页获取用户列表
     *
     * @param pageable 分页信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.list')")
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, UserEntity entity, @NonNull Principal user) {
        LambdaQueryChainWrapper<UserEntity> lambdaQuery = buildLambdaQuery(entity);
        // 排除当前登录用户信息
        lambdaQuery.ne(UserEntity::getId, user.getName());
        OrganizationUtils.includes(lambdaQuery, UserEntity::getOrgId);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<UserEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 新增用户信息
     *
     * @param entity 用户数据对象
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.add')")
    @PostMapping
    public ResponseEntity<?> save(@Validated @RequestBody UserEntity entity, BindingResult bindingResult) throws BindException {
        if (bindingResult.hasErrors()) {
            throw new BindException(bindingResult);
        }
        userService.saveUser(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, entity.getId());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 获取用户详细信息
     *
     * @param userId 用户ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.info')")
    @GetMapping("/{userId}")
    public Object info(@PathVariable String userId) {
        UserEntity entity = userService.getUserInfo(userId, false, UserService.UserInfoEnum.ALL);
        return success(entity);
    }

    /**
     * 修改用户信息（目前只支持修改昵称）
     *
     * @param userId 用户ID
     * @param entity 新的用户信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.update')")
    @PutMapping("/{userId}")
    public ResponseEntity<?> put(@PathVariable String userId, @Validated @RequestBody UserEntity entity, BindingResult bindingResult) throws BindException {
        if (bindingResult.hasErrors()) {
            throw new BindException(bindingResult);
        }
        entity.setId(userId);
        userService.updateUser(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.delete')")
    @DeleteMapping("/{userId}")
    public ResponseEntity<?> delete(@PathVariable String userId) {
        userService.deleteUser(userId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>部门信息</strong>
     *
     * @param ids  主键ID列表
     * @param user 当前登录用户信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.delete')")
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids, @NonNull Principal user) {
        // 不能通过该接口删除当前登录用户信息
        ids.remove(user.getName());
        userService.deleteUser(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 修改用户密码
     *
     * @param userId           用户ID
     * @param resetPasswordDTO 新旧密码信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.update-password')")
    @PutMapping("/{userId}/update-password")
    public ResponseEntity<?> updatePassword(@PathVariable String userId, @Validated @RequestBody ResetPasswordDTO resetPasswordDTO, BindingResult bindingResult) throws BindException {
        if (bindingResult.hasErrors()) {
            throw new BindException(bindingResult);
        }
        userService.updatePassword(userId, resetPasswordDTO.getOldPassword(), resetPasswordDTO.getNewPassword());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 新密码信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.reset-password')")
    @PutMapping("/{userId}/reset-password")
    public ResponseEntity<?> resetPassword(@PathVariable String userId, String password) {
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("新密码不能为空");
        }
        userService.updatePassword(userId, password);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 获取某个用户的角色列表
     *
     * @param userId 用户ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.config-roles')")
    @GetMapping("{userId}/roles")
    public Object getUserRoles(@PathVariable String userId) {
        return success(roleService.getUserRoles(userId));
    }

    /**
     * 设置某个用户的角色列表（给用户分配角色）
     *
     * @param userId 用户ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.config-roles')")
    @PutMapping("{userId}/roles")
    public Object setUserRoles(@PathVariable String userId, @RequestBody List<RoleEntity> roleEntities) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(userId);
        userEntity.setRoles(roleEntities);
        userService.setUserRoles(userEntity);

        return success(null);
    }

    /**
     * 获取某个用户的权限列表
     *
     * @param userId 用户ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.config-permissions')")
    @GetMapping("{userId}/permissions")
    public Object getUserPermissions(@PathVariable String userId) {
        return success(permissionService.getUserPermissions(userId));
    }

    /**
     * 设置某个用户的权限列表（给用户分配权限）
     *
     * @param userId 用户ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER') or hasAnyAuthority('user.config-permissions')")
    @PutMapping("{userId}/permissions")
    public Object setUserPermissions(@PathVariable String userId, @RequestBody List<PermissionEntity> permissionEntities) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(userId);
        userEntity.setPermissions(permissionEntities);
        userService.setUserPermissions(userEntity);

        return success(null);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<UserEntity> buildLambdaQuery(UserEntity entity) {
        LambdaQueryChainWrapper<UserEntity> lambdaQuery = userService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), UserEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getNickname()), UserEntity::getNickname, entity.getNickname());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUsername()), UserEntity::getUsername, entity.getUsername());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPhone()), UserEntity::getPhone, entity.getPhone());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getEmail()), UserEntity::getEmail, entity.getEmail());
        return lambdaQuery;
    }
}
